package data

import (
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	"strconv"
)

type OrderRepo struct{}

type InvoiceDto struct {
	Id              int     `orm:"pk;auto;column(id)"`
	Title           string  `orm:"column(title)"`
	Addr            string  `orm:"column(post_addr)"`
	RecvName        string  `orm:"column(recv_name)"`
	InsuranceAmount float32 `orm:"column(insurance_amount)"`
	GuaranteeAmount float32 `orm:"column(guarantee_amount)"`
	Amount          float32 `orm:"column(amount)"`
	TaxNo           string  `orm:"column(tax_no)"`
	RecvPhone       string  `orm:"column(recv_phone)"`
	ZipCode         string  `orm:"column(zip_code)"`
	WaybillId       int     `orm:"column(waybill_id)"`
	MemberId        int     `orm:"column(member_id)"`
	CorpId          int     `orm:"column(corp_id)"`
	State           int     `orm:"column(state)"`
	BankOfDeposit   string  `orm:"column(bank_of_deposit)"`
	BankCardNo      string  `orm:"column(bank_card_no)"`
	PayeeName       string  `orm:"column(payee_name)"`
	PayeeIDCard     string  `orm:"column(payee_idcard)"`
	ApplyTime       string  `orm:"column(apply_time)"`
}

func (dto *InvoiceDto) TableName() string {
	return "o_invoice"
}

func (repo OrderRepo) OrderExistsThenDelete(remark string) {
	if len(remark) != 0 {
		o := orm.NewOrm()
		o.Raw("delete from l_carrier_pub where id in (select carrier_pub_id from o_waybill where remark = ?)", remark).Exec()
		o.Raw("delete from o_contract where waybill_id in (select id from o_waybill where remark = ?)", remark).Exec()
		o.Raw("delete from o_invoice where waybill_id in (select id from o_waybill where  remark = ?)", remark).Exec()
		o.Raw("delete from t_pay_offline where waybill_id in (select id from o_waybill where  remark = ?)", remark).Exec()
		o.Raw("delete from o_waybill_message where waybill_id in (select id from o_waybill where remark = ?)", remark).Exec()
		o.Raw("delete from o_waybill_score where waybill_id in (select id from o_waybill where remark = ?)", remark).Exec()
		o.Raw("delete from o_waybill where remark = ?", remark).Exec()
	}
}

func (repo OrderRepo) GetInvoice(waybillId int) (InvoiceDto, error) {
	var invoice InvoiceDto
	o := orm.NewOrm()
	err := o.Raw(SQL_Order_Get_Invoice, waybillId).QueryRow(&invoice)
	return invoice, err
}

func (repo OrderRepo) PayInvoiceOk(waybillId int) (err error) {
	o := orm.NewOrm()
	_, err = o.QueryTable("o_invoice").
		Filter("waybill_id", waybillId).
		Update(orm.Params{"State": 1})
	return
}

func (repo OrderRepo) CancelInvoice(waybillId int) (err error) {
	o := orm.NewOrm()
	_, err = o.QueryTable("o_invoice").
		Filter("waybill_id", waybillId).
		Update(orm.Params{"State": 2})
	return
}

func (repo OrderRepo) UpdateInvoiceAmount(waybillId int, amount, insuranceAmount, guaranteeAmount float32) (err error) {
	o := orm.NewOrm()
	_, err = o.QueryTable("o_invoice").
		Filter("waybill_id", waybillId).
		Update(orm.Params{"Amount": amount, "InsuranceAmount": insuranceAmount, "GuaranteeAmount": guaranteeAmount})
	return
}

func (repo OrderRepo) TotalInvoiceAmount() (float64, error) {
	var err error
	var sum float64
	var list orm.ParamsList
	o := orm.NewOrm()
	if _, err = o.Raw(SQL_Invoice_SUM).ValuesFlat(&list); err == nil {
		sum, _ = strconv.ParseFloat(list[0].(string), 32)
	}
	return sum, err
}

func (repo OrderRepo) UpdateInvoice(memberId, waybillId int, invoice InvoiceDto) error {
	o := orm.NewOrm()
	_, err := o.QueryTable("o_invoice").
		Filter("WaybillId", waybillId).
		Filter("MemberId", memberId).
		Update(orm.Params{
			"Title":         invoice.Title,
			"Addr":          invoice.Addr,
			"RecvName":      invoice.RecvName,
			"ZipCode":       invoice.ZipCode,
			"RecvPhone":     invoice.RecvPhone,
			"TaxNo":         invoice.TaxNo,
			"BankOfDeposit": invoice.BankOfDeposit,
			"BankCardNo":    invoice.BankCardNo,
		})
	return err
}

func (r OrderRepo) GetScoreAndOrderCount(memberID int) (string, string, error) {
	var err error
	var list orm.ParamsList
	var scoreCount, orderCount string
	o := orm.NewOrm()
	if _, err = o.Raw(SQL_Mbr_Score_Order_Count, memberID, memberID).ValuesFlat(&list); err == nil {
		scoreCount = list[0].(string)
		orderCount = list[1].(string)
	}
	return scoreCount, orderCount, err
}

func init() {
	orm.RegisterModel(new(InvoiceDto))
}
